package com.etc.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import com.etc.entity.Admins;
import com.etc.entity.Employees;
import com.etc.service.impl.AdminServiceImpl;
import com.etc.util.MD5Util;
import com.google.gson.Gson;

/**
 * Servlet implementation class AdminController
 */
@WebServlet("/AdminController")
@MultipartConfig
public class AdminController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	AdminServiceImpl as=new AdminServiceImpl();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AdminController() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		String op=request.getParameter("op");
		HttpSession session = request.getSession();
		//查看请求域中包含的参数
		/*Map<String, String[]> map = request.getParameterMap();
		Set<String> set = map.keySet();
		for (String key : set) {
			String[] value = map.get(key);
			System.out.println(key+":"+Arrays.toString(value));
		}*/
		
		if ("login".equals(op)) {
			adminLogin(request,response);
			
		} else if ("addAdmin".equals(op)) {
			//调用添加员工的方法
			addAdmin(request, response);
		}else if ("adminQuit".equals(op)) {
			//调用管理员退出方法
			adminQuit(request,response);
		}else if ("removeAdmin".equals(op)) {
			//调用移除管理员的方法,就是把表中adminStatus字段改为0
			removeAdmin(request,response);
		} else if ("change_admin_pwd".equals(op)) {
			// 调用更改管理员密码的方法
			changeAdminPwd(request, response);
		}else if("updatePic".equals(op)){
			updatePic(request,session,response);
		}
		
	}
    
  //修改头像
  	private void updatePic(HttpServletRequest request, HttpSession session, HttpServletResponse response) throws IOException, ServletException {
  		response.setContentType("application/json;utf-8");
  		Part part = request.getPart("ep");
  		System.out.println("part:" + part);
  		PrintWriter writer = response.getWriter();
  		if(part == null) {
  			return;
  		}
  		String path = loadPhoto(part, request, response);
  		Admins admin = (Admins)session.getAttribute("admin");
  		String oldPath = admin.getAdminAvatarAddr();
  		admin.setAdminAvatarAddr(path);
  		boolean flag = as.modifAdminPic(admin);
  		if(flag) {
  			File file = new File("D:\\images\\" + oldPath);
  			if(file.exists()) {
  				file.delete();
  			}
  			session.setAttribute("admin", admin);
  			Gson gson = new Gson();
  			String json = gson.toJson(admin);
  			writer.print(json);
  		}
  		
  		writer.close();
  	}

    private void changeAdminPwd(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 通过Ajax请求发过来的账户和密码
		String previousPwd = request.getParameter("previousPwd");
		String newPwd = request.getParameter("newPwd");

		// 直接通过session取admin
		Admins admin = (Admins) request.getSession().getAttribute("admin");
		// System.out.println(admin);
		String adminPwd = admin.getAdminPwd();
		String doubleEncryption = MD5Util.doubleEncryption(previousPwd);
		
		if (!adminPwd.equals(doubleEncryption)) {
			response.getWriter().print(false);
		} else {
			boolean flag = as.changeAdminPwd(admin, newPwd);
			// 通过ajx返回json数据
			Gson gson = new Gson();
			String jsonFlag = gson.toJson(flag);
			response.getWriter().print(jsonFlag);
		}
	
		response.getWriter().close();

	}

	private void removeAdmin(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		String adminName = request.getParameter("adminNameF2");
		String adminPwd = request.getParameter("adminPwd1F2");
		
		boolean flag = as.removeAdmin(adminName, adminPwd);
		if (flag) {
			response.getWriter().print("注销成功");
		} else {
			response.getWriter().print("账户密码错误");
		}
		
	}

	private void adminQuit(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		request.removeAttribute("adminName");
		request.getSession().removeAttribute("admin");
		response.sendRedirect("adminLogin.jsp");
	}

	/**
	 * 管理员登录的方法
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	private void adminLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String adminName = request.getParameter("adminName");
		String adminPwd = request.getParameter("adminPwd");
		
		HttpSession session = request.getSession();
		Admins admin=as.queryAdminByName(adminName, adminPwd);
		System.out.println(admin);
		if (admin!=null) {
			if (admin.getAdminStatus()==1) {
				String reme=request.getParameter("autoLogin");
				if (reme!=null) {
					System.out.println("用户选择记住密码"+reme);
					Cookie cookie1=new Cookie("adminname", adminName);
					Cookie cookie2=new Cookie("adminpwd", adminPwd);
					Cookie cookie3=new Cookie("adminchecked","checked" );
					cookie1.setMaxAge(240);
					cookie2.setMaxAge(240);
					cookie3.setMaxAge(240);
					response.addCookie(cookie1);
					response.addCookie(cookie2);
					response.addCookie(cookie3);
				}
				session.setAttribute("admin", admin);
				response.sendRedirect("Admin/Index.jsp");
			} else {
				response.getWriter().print("<script>alert('该用户已注销');location.href='adminLogin.jsp'</script>");
			}
			
		} else {
			response.getWriter().print("<script>alert('账户密码错误');location.href='adminLogin.jsp'</script>");
		}
	}

	private void addAdmin(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		// TODO Auto-generated method stub
		String adminName = request.getParameter("adminNameF1");
		String adminPwd = request.getParameter("adminPwd1F1");
		//获得上传的图片文件
		Part part = request.getPart("myPhotoF11");
		//上传文件到服务器img文件夹
		String photePath = loadPhoto(part,request,response);
		//调用业务层在表中创建对象
		Admins admin = new Admins(adminName, adminPwd, photePath);
		//加入对象进入到表中
		boolean flag = as.addAdmin(admin);
		if (flag) {
			response.getWriter().print("添加管理员成功");
		} else {
			response.getWriter().print("添加失败");
		}
	}

	
	/**
	 * 上传文件的方法
	 * @param part 文件对象
	 * @throws IOException
	 */
	private String loadPhoto(Part part,HttpServletRequest request, HttpServletResponse response) throws IOException {
				//通过请求头和拼接获得真实的图片名
				String header = part.getHeader("content-disposition");
				System.out.println(header);
				String realName=header.substring(header.indexOf("filename=")+10,header.length()-1);
				System.out.println(realName);
				//添加uuid
				UUID uuid = UUID.randomUUID();
				String uuidRealName=uuid+realName;
				System.out.println(uuidRealName);
				//拼接完整文件名
//				String photePath=request.getServletContext().getRealPath("/") + "dist\\img\\" +uuidRealName;
				
				String photePath="D:\\images\\" + uuidRealName;
				System.out.println(photePath);
				//写入文件
				part.write(photePath);
				//此处返回的是文件的路径片段
				return uuidRealName;
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
